<template>
  <div class="orders-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <h2 class="orders-title">采购订单管理</h2>
          <div class="header-controls">
            <el-input
              v-model="searchQuery"
              placeholder="搜索订单"
              style="width: 200px; margin-right: 10px"
            />
            <el-button type="primary" @click="handleCreateOrder">创建订单</el-button>
            <el-button type="success" @click="handleExport" style="margin-left: 10px">导出报表</el-button>
          </div>
        </div>
      </template>

      <el-table :data="filteredOrders" style="width: 100%">
        <el-table-column prop="order_number" label="订单编号" width="180" />
        <el-table-column prop="supplier" label="供应商" />
        <el-table-column label="采购商品" min-width="100">
          <template #default="{ row }">
            <div v-if="row.items && row.items.length">
              <div v-for="item in row.items" :key="item.id" class="product-info">
                <span class="product-name">{{ item.product_name }}</span>
                <span class="quantity">x {{ item.quantity }}</span>
              </div>
            </div>
            <span v-else>暂无商品信息</span>
          </template>
        </el-table-column>
        <el-table-column prop="total_amount" label="总金额">
          <template #default="{ row }">
            ¥{{ Number(row.total_amount).toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">{{ getOrderStatus(row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="created_at" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDateTime(row.created_at) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleView(row)">查看</el-button>
            <el-button 
              v-if="row.status === 'pending'"
              type="success" 
              size="small" 
              @click="handleConfirm(row)"
            >确认</el-button>
            <el-button 
              v-if="row.status === 'confirmed'"
              type="success" 
              size="small" 
              @click="handleReceive(row)"
            >收货</el-button>
            <el-button 
              v-if="row.status === 'pending'"
              type="danger" 
              size="small" 
              @click="handleCancel(row)"
            >取消</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="totalOrders"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 创建订单对话框 -->
    <el-dialog v-model="dialogVisible" title="创建采购订单" width="800px">
      <el-form ref="orderFormRef" :model="orderForm" :rules="rules" label-width="100px">
        <el-form-item label="产品列表" prop="items">
          <div v-for="(product, index) in orderForm.items" :key="index" class="product-item">
            <el-select v-model="product.product_id" placeholder="选择产品" style="width: 200px" size="small" @change="handleProductChange(product, index)">
              <el-option
                v-for="p in availableProducts"
                :key="p.id"
                :label="p.name"
                :value="p.id"
              />
            </el-select>
            <el-input-number 
              v-model="product.quantity" 
              :min="1" 
              placeholder="数量"
              size="small"
              style="width: 120px"
              @change="handleQuantityChange(product.quantity, index)"
            />
            <el-select v-model="product.warehouse_id" placeholder="选择入库仓库" style="width: 200px" size="small">
              <el-option
                v-for="warehouse in warehouses"
                :key="warehouse.id"
                :label="warehouse.name"
                :value="warehouse.id"
              />
            </el-select>
            <el-button type="danger" size="small" @click="removeProduct(index)">删除</el-button>
          </div>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" size="small" @click="addProduct">添加产品</el-button>
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="orderForm.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 查看订单详情对话框 -->
    <el-dialog v-model="viewDialogVisible" title="订单详情" width="800px">
      <div v-if="currentOrder" class="order-details">
        <div class="detail-item"><span class="label">订单编号：</span>{{ currentOrder.order_number }}</div>
        <div class="detail-item"><span class="label">供应商：</span>{{ currentOrder.supplier }}</div>
        <div class="detail-item"><span class="label">总金额：</span>¥{{ Number(currentOrder.total_amount).toFixed(2) }}</div>
        <div class="detail-item"><span class="label">状态：</span><el-tag :type="getStatusType(currentOrder.status)">{{ getOrderStatus(currentOrder.status) }}</el-tag></div>
        <div class="detail-item"><span class="label">创建时间：</span>{{ formatDateTime(currentOrder.created_at) }}</div>
        <div class="detail-item"><span class="label">备注：</span>{{ currentOrder.remark }}</div>

        <el-table :data="currentOrder.items" style="width: 100%; margin-top: 20px">
          <el-table-column label="产品名称">
            <template #default="{ row }">
              {{ row.product_name || (row.product && row.product.name) || '未知' }}
            </template>
          </el-table-column>
          <el-table-column prop="quantity" label="数量" />
          <el-table-column prop="unit_price" label="单价">
            <template #default="{ row }">¥{{ Number(row.unit_price).toFixed(2) }}</template>
          </el-table-column>
          <el-table-column prop="total_price" label="小计">
            <template #default="{ row }">¥{{ Number(row.total_price).toFixed(2) }}</template>
          </el-table-column>
        </el-table>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, h } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'
import { getToken } from '@/utils/auth'
import { useProductStore } from '@/stores/productStore'

// 配置 axios 默认值
axios.defaults.baseURL = 'http://localhost:8000'
axios.defaults.timeout = 15000
axios.defaults.withCredentials = true

const searchQuery = ref('')
const orders = ref([])
const warehouses = ref([])
const dialogVisible = ref(false)
const viewDialogVisible = ref(false)
const currentOrder = ref(null)
const orderFormRef = ref()
const orderForm = ref({
  supplier: '优质生鲜供应有限公司',
  items: [{
    product_id: '',
    quantity: 1,
    unit_price: 0.01,
    warehouse_id: ''
  }],
  remark: ''
})

const rules = {
  items: [{ required: true, message: '请至少添加一个产品', trigger: 'change' }]
}

const productStore = useProductStore()
const availableProducts = computed(() => productStore.products.map(p => ({
  id: p.id,
  name: p.name,
  price: p.price
})))

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const totalOrders = ref(0)

// 获取仓库列表
const fetchWarehouses = async () => {
  try {
    const token = getToken()
    if (!token) {
      ElMessage.warning('请先登录')
      return
    }

    const response = await axios.get('/api/warehouses/', {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    })
    
    console.log('获取仓库列表响应:', response.data)
    
    // 处理不同的响应格式
    if (Array.isArray(response.data)) {
      warehouses.value = response.data
    } else if (response.data?.results && Array.isArray(response.data.results)) {
      warehouses.value = response.data.results
    } else if (Array.isArray(response.data?.data)) {
      warehouses.value = response.data.data
    } else {
      warehouses.value = []
      console.warn('未能识别的仓库数据格式:', response.data)
    }
  } catch (error) {
    console.error('获取仓库列表失败:', error)
    ElMessage.error('获取仓库列表失败')
    warehouses.value = []
  }
}

// 获取订单列表
const fetchOrders = async () => {
  try {
    const token = getToken()
    if (!token) {
      ElMessage.warning('请先登录')
      return false
    }

    const response = await axios.get('/api/purchase-orders/', {
      params: {
        page: currentPage.value,
        limit: pageSize.value
      },
      headers: {
        'Authorization': `Bearer ${token}`
      }
    })

    console.log('获取订单列表响应:', response.data)

    // 处理不同的响应格式
    let orderList = []
    let total = 0

    if (response.data?.data?.items) {
      orderList = response.data.data.items
      total = response.data.data.total || 0
    } else if (response.data?.data?.results) {
      orderList = response.data.data.results
      total = response.data.data.total || 0
    } else if (Array.isArray(response.data?.data)) {
      orderList = response.data.data
      total = response.data.total || orderList.length
    } else if (Array.isArray(response.data?.results)) {
      orderList = response.data.results
      total = response.data.total || orderList.length
    } else if (Array.isArray(response.data)) {
      orderList = response.data
      total = orderList.length
    }

    // 确保每个订单对象都有必需的字段
    orders.value = orderList.map(order => ({
      id: order.id,
      order_number: order.order_number || '',
      supplier: order.supplier || '',
      total_amount: order.total_amount || 0,
      status: order.status || 'pending',
      created_at: order.created_at || new Date().toISOString(),
      items: Array.isArray(order.items) ? order.items.map(item => ({
        ...item,
        product_name: item.product_name || (item.product && item.product.name) || '未知产品'
      })) : [],
      remark: order.remark || ''
    }))

    totalOrders.value = total
    return true
  } catch (error) {
    console.error('获取订单列表失败:', error.response || error)
    ElMessage.error(error.response?.data?.message || '获取订单列表失败')
    orders.value = []
    totalOrders.value = 0
    return false
  }
}

// 创建订单
const handleSubmit = async () => {
  try {
    await orderFormRef.value.validate()
    
    if (!orderForm.value.items.length) {
      ElMessage.warning('请至少添加一个产品')
      return
    }

    const invalidProducts = orderForm.value.items.filter(p => !p.product_id || !p.warehouse_id || p.quantity <= 0)
    if (invalidProducts.length) {
      ElMessage.warning('请确保所有产品都已选择且数量大于0，并选择入库仓库')
      return
    }

    // 构建items数组，确保每个字段都是正确的类型
    const items = orderForm.value.items.map(p => {
      // 确保所有字段都存在且类型正确
      if (!p.product_id || !p.warehouse_id || !p.quantity) {
        throw new Error('商品信息不完整')
      }

      // 确保数据类型正确
      const product_id = String(parseInt(p.product_id))
      const warehouse_id = String(parseInt(p.warehouse_id))
      const quantity = String(parseInt(p.quantity))

      // 验证数据有效性
      if (isNaN(parseInt(product_id)) || parseInt(product_id) <= 0) {
        throw new Error('商品ID无效')
      }

      if (isNaN(parseInt(warehouse_id)) || parseInt(warehouse_id) <= 0) {
        throw new Error('仓库ID无效')
      }

      if (isNaN(parseInt(quantity)) || parseInt(quantity) <= 0) {
        throw new Error('数量必须大于0')
      }

      // 获取商品的采购价
      const productInfo = availableProducts.value.find(p => p.id === parseInt(product_id))
      const unit_price = String(productInfo ? productInfo.price : '0.01')

      return {
        product_id,
        quantity,
        unit_price,
        warehouse_id
      }
    })

    const postData = {
      supplier: '优质生鲜供应有限公司',
      items,
      remark: orderForm.value.remark || ''
    }

    console.log('创建订单数据:', JSON.stringify(postData, null, 2))
    console.log('商品数据类型:', items.map(item => ({
      product_id: typeof item.product_id + ' = ' + item.product_id,
      quantity: typeof item.quantity + ' = ' + item.quantity,
      unit_price: typeof item.unit_price + ' = ' + item.unit_price,
      warehouse_id: typeof item.warehouse_id + ' = ' + item.warehouse_id
    })))

    const token = getToken()
    if (!token) {
      ElMessage.warning('请先登录')
      return
    }

    const response = await axios.post('/api/purchase-orders/', postData, {
      headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json'
      }
    })

    if (response.data?.code === 200) {
      ElMessage.success('订单创建成功')
      dialogVisible.value = false
      await fetchOrders()
      orderForm.value = {
        supplier: '优质生鲜供应有限公司',
        items: [{
          product_id: '',
          quantity: 1,
          unit_price: '0.01',
          warehouse_id: ''
        }],
        remark: ''
      }
    } else {
      throw new Error(response.data?.message || '创建订单失败')
    }
  } catch (error) {
    console.error('创建订单失败:', error)
    ElMessage.error(error.response?.data?.message || error.message || '创建订单失败')
  }
}

// 查看订单详情
const handleView = async (row) => {
  try {
    const token = getToken()
    if (!token) {
      ElMessage.warning('请先登录')
      return
    }

    const response = await axios.get(`/api/purchase-orders/${row.id}/`, {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    })

    currentOrder.value = response.data
    viewDialogVisible.value = true
  } catch (error) {
    console.error('获取订单详情失败:', error)
    ElMessage.error('获取订单详情失败')
  }
}

// 确认订单
const handleConfirm = async (order) => {
  try {
    await ElMessageBox.confirm('确认此采购订单?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const token = getToken()
    if (!token) {
      ElMessage.warning('请先登录')
      return
    }

    await axios.put(`/api/purchase-orders/${order.id}/status/`, {
      status: 'confirmed'
    }, {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    })

    ElMessage.success('订单已确认')
    await fetchOrders()
  } catch (error) {
    if (error === 'cancel') return
    console.error('确认订单失败:', error)
    ElMessage.error('确认订单失败')
  }
}

// 收货处理
const handleReceive = async (order) => {
  try {
    await ElMessageBox.confirm('确认收货此采购订单?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
      message: h('div', null, [
        h('p', null, '收货后将：'),
        h('ul', null, [
          h('li', null, '更新订单状态为已收货'),
          h('li', null, '增加相应商品的库存'),
          h('li', null, '生成入库记录')
        ])
      ])
    })

    const token = getToken()
    if (!token) {
      ElMessage.warning('请先登录')
      return
    }

    await axios.put(`/api/purchase-orders/${order.id}/status/`, {
      status: 'received'
    }, {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    })

    ElMessage.success('订单已收货')
    await fetchOrders()
  } catch (error) {
    if (error === 'cancel') return
    console.error('收货失败:', error)
    ElMessage.error('收货失败')
  }
}

// 取消订单
const handleCancel = async (order) => {
  try {
    await ElMessageBox.confirm('确认取消此采购订单?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
      message: h('div', null, [
        h('p', null, '取消后：'),
        h('ul', null, [
          h('li', null, '订单状态将更新为已取消'),
          h('li', null, '该订单将不能再进行其他操作')
        ])
      ])
    })

    const token = getToken()
    if (!token) {
      ElMessage.warning('请先登录')
      return
    }

    await axios.put(`/api/purchase-orders/${order.id}/status/`, {
      status: 'cancelled'
    }, {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    })

    ElMessage.success('订单已取消')
    await fetchOrders()
  } catch (error) {
    if (error === 'cancel') return
    console.error('取消订单失败:', error)
    ElMessage.error('取消订单失败')
  }
}

const addProduct = () => {
  if (orderForm.value.items.length >= 10) {
    ElMessage.warning('单次最多添加10个产品')
    return
  }
  orderForm.value.items.push({
    product_id: '',
    quantity: 1,
    unit_price: 0.01,
    warehouse_id: ''
  })
}

const removeProduct = index => {
  orderForm.value.items.splice(index, 1)
}

const handleCreateOrder = () => {
  orderForm.value = {
    supplier: '优质生鲜供应有限公司',
    items: [{
      product_id: '',
      quantity: 1,
      unit_price: 0.01,
      warehouse_id: ''
    }],
    remark: ''
  }
  dialogVisible.value = true
}

const getOrderStatus = (status) => {
  const statusMap = {
    'pending': '待确认',
    'confirmed': '已确认',
    'received': '已收货',
    'cancelled': '已取消',
    'completed': '已完成'
  }
  return statusMap[status] || status || '未知'
}

const getStatusType = status => ({
  'pending': 'warning',
  'confirmed': 'primary',
  'received': 'success',
  'cancelled': 'info',
  'completed': 'success'
}[status] || 'info')

const handleProductChange = (product, index) => {
  if (product) {
    const existingProduct = orderForm.value.items.find((p, i) => i !== index && p.product_id === product.id)
    if (existingProduct) {
      ElMessage.warning('该产品已添加，请勿重复选择')
      orderForm.value.items[index].product_id = ''
      return
    }

    const productInfo = availableProducts.value.find(p => p.id === product.id)
    if (productInfo) {
      orderForm.value.items[index] = {
        ...orderForm.value.items[index],
        product_id: product.id
      }
    }
  }
}

const handleQuantityChange = (value, index) => {
  if (value <= 0) {
    ElMessage.warning('数量必须大于0')
    orderForm.value.items[index].quantity = 1
    return
  }
  orderForm.value.items[index].quantity = parseInt(value)
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchOrders()
}

const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1 // 重置到第一页
  fetchOrders()
}

const handleSearch = () => {
  currentPage.value = 1
  fetchOrders()
}

const filteredOrders = computed(() => {
  if (!searchQuery.value) return orders.value
  const q = searchQuery.value.toLowerCase()
  return orders.value.filter(o =>
    (o.order_number?.toLowerCase() || '').includes(q) ||
    (o.supplier?.toLowerCase() || '').includes(q)
  )
})

function formatDateTime(dateStr) {
  if (!dateStr) return ''
  const d = new Date(dateStr)
  if (isNaN(d.getTime())) return dateStr
  const pad = n => String(n).padStart(2, '0')
  return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`
}

// 导出报表
const handleExport = async () => {
  try {
    const token = getToken()
    if (!token) {
      ElMessage.warning('请先登录')
      return
    }

    // 获取所有订单数据
    const response = await axios.get('/api/purchase-orders/', {
      params: {
        page: 1,
        limit: 1000 // 获取更多数据用于导出
      },
      headers: {
        'Authorization': `Bearer ${token}`
      }
    })

    let orderList = []
    if (response.data?.data?.items) {
      orderList = response.data.data.items
    } else if (response.data?.data?.results) {
      orderList = response.data.data.results
    } else if (Array.isArray(response.data?.data)) {
      orderList = response.data.data
    } else if (Array.isArray(response.data?.results)) {
      orderList = response.data.results
    } else if (Array.isArray(response.data)) {
      orderList = response.data
    }

    // 处理数据为CSV格式
    const headers = ['订单编号', '供应商', '总金额', '状态', '创建时间', '备注']
    const rows = orderList.map(order => [
      order.order_number || '',
      order.supplier || '',
      `¥${Number(order.total_amount || 0).toFixed(2)}`,
      getOrderStatus(order.status),
      formatDateTime(order.created_at),
      order.remark || ''
    ])

    // 添加商品明细
    const detailRows = []
    orderList.forEach(order => {
      if (order.items && order.items.length) {
        order.items.forEach(item => {
          detailRows.push([
            order.order_number || '',
            item.product_name || (item.product && item.product.name) || '未知产品',
            item.quantity || 0,
            `¥${Number(item.unit_price || 0).toFixed(2)}`,
            `¥${Number(item.total_price || 0).toFixed(2)}`
          ])
        })
      }
    })

    // 创建CSV内容
    let csvContent = '订单概览\n'
    csvContent += headers.join(',') + '\n'
    rows.forEach(row => {
      csvContent += row.join(',') + '\n'
    })

    csvContent += '\n订单明细\n'
    csvContent += '订单编号,商品名称,数量,单价,小计\n'
    detailRows.forEach(row => {
      csvContent += row.join(',') + '\n'
    })

    // 创建Blob对象
    const blob = new Blob(['\ufeff' + csvContent], { type: 'text/csv;charset=utf-8;' })
    const link = document.createElement('a')
    const url = URL.createObjectURL(blob)
    
    // 设置下载链接
    link.setAttribute('href', url)
    link.setAttribute('download', `采购订单报表_${formatDateTime(new Date()).replace(/[\/\s:]/g, '_')}.csv`)
    link.style.visibility = 'hidden'
    
    // 触发下载
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    
    ElMessage.success('报表导出成功')
  } catch (error) {
    console.error('导出报表失败:', error)
    ElMessage.error('导出报表失败')
  }
}

onMounted(async () => {
  await productStore.initialize()
  await fetchOrders()
  await fetchWarehouses()
})
</script>

<style scoped>
.orders-container {
  padding: 20px;
}

.orders-title {
  margin: 0 0 10px 0;
  font-size: 24px;
  color: #303133;
  font-weight: 700;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.header-controls {
  display: flex;
  align-items: center;
}
.product-item {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 10px;
}
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
.order-details {
  padding: 20px;
}
.detail-item {
  margin-bottom: 15px;
}
.detail-item .label {
  font-weight: bold;
  margin-right: 10px;
}
.product-info {
  display: flex;
  align-items: center;
  margin-bottom: 4px;
}
.product-info:last-child {
  margin-bottom: 0;
}
.product-name {
  width: 80px;
  text-align: left;
  padding-right: 8px;
}
.product-info .quantity {
  color: #666;
}
.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>
